package com.everflourish.yeah100.utils.collections;

import com.everflourish.yeah100.entity.statistics.ObjectiveTopic;
import com.everflourish.yeah100.utils.StringUtil;

import java.util.Comparator;

/**
 * 统计分析-成绩排序
 *
 * @author pf
 * @date 2015-3-16
 */
public class FailureRateCollections implements Comparator<ObjectiveTopic> {

    /**
     * 比较错误率题号的标记
     */
    public static final int COMPARE_TOPIC_NO = 1;
    /**
     * 比较错误率标记
     */
    public static final int COMPARE_FAILURE_RATE = 2;

    private int mFlag = COMPARE_TOPIC_NO;// 标记，默认为题号
    // 是否是降序排序
    private boolean isDesc = false;

    public FailureRateCollections(boolean isDesc, int flag) {
        this.isDesc = isDesc;
        this.mFlag = flag;
    }

    @Override
    public int compare(ObjectiveTopic lhsObjectiveTopic,
                       ObjectiveTopic rhsObjectiveTopic) {
        int compareFlag = 0;
        switch (mFlag) {
            case COMPARE_TOPIC_NO:
                compareFlag = compareTopicNo(lhsObjectiveTopic, rhsObjectiveTopic);
                break;
            case COMPARE_FAILURE_RATE:
                double lhsFailureRate = lhsObjectiveTopic.getFailureRate();
                double rhsFailureRate = rhsObjectiveTopic.getFailureRate();
                if (isDesc) {
                    if (lhsFailureRate > rhsFailureRate) {
                        compareFlag = -1;
                    } else if (lhsFailureRate < rhsFailureRate) {
                        compareFlag = 1;
                    } else {
                        compareFlag = compareTopicNo(lhsObjectiveTopic,
                                rhsObjectiveTopic);
                    }
                } else {
                    if (lhsFailureRate > rhsFailureRate) {
                        compareFlag = 1;
                    } else if (lhsFailureRate < rhsFailureRate) {
                        compareFlag = -1;
                    } else {
                        compareFlag = compareTopicNo(lhsObjectiveTopic,
                                rhsObjectiveTopic);
                    }
                }
                break;
        }
        return compareFlag;
    }

    /**
     * 比较题号
     *
     * @param lhsObjectiveTopic
     * @param rhsObjectiveTopic
     * @return
     */
    private int compareTopicNo(ObjectiveTopic lhsObjectiveTopic,
                               ObjectiveTopic rhsObjectiveTopic) {
        int compareFlag;
        int lhsSequenceNo = StringUtil.parseInt(
                lhsObjectiveTopic.getSequenceNo(), -1);
        int rhsSequenceNo = StringUtil.parseInt(
                rhsObjectiveTopic.getSequenceNo(), -1);
        if (isDesc) {
            compareFlag = -(lhsSequenceNo - rhsSequenceNo);
        } else {
            compareFlag = lhsSequenceNo - rhsSequenceNo;
        }
        return compareFlag;
    }
}
